package org.jpro.modules.system.web;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.jpro.common.web.BaseController;
import org.jpro.modules.system.entity.Role;
import org.jpro.modules.system.entity.User;
import org.jpro.modules.system.service.IRolePermissionService;
import org.jpro.modules.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 角色controller
 */
@Controller
@RequestMapping("/system/role")
public class RoleController extends BaseController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRolePermissionService rolePermissionService;

    /**
     * 默认页面
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String list() {
        return "system/roleList";
    }

    /**
     * 角色集合(JSON)
     */
    @ResponseBody
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "json", method = RequestMethod.GET)
    public Map<String, Object> getData() {
        return getEasyUIData(roleService.search(super.getPageRequest()));
    }

    /**
     * 获取角色拥有的权限ID集合
     */
    @ResponseBody
    @RequestMapping("{id}/json")
    @RequiresPermissions("sys:role:permView")
    public List<Integer> getRolePermissions(@PathVariable("id") Integer id) {
        List<Integer> permissionIdList = rolePermissionService.getPermissionIds(id);
        return permissionIdList;
    }

    /**
     * 修改角色权限
     */
    @ResponseBody
    @RequiresPermissions("sys:role:permUpd")
    @RequestMapping(value = "{id}/updatePermission")
    public void updateRolePermission(@PathVariable("id") Integer id, @RequestBody List<Integer> newRoleIdList, HttpSession session) {
        List<Integer> oldRoleIdList = rolePermissionService.getPermissionIds(id);

        // 获取application中的sessions
        @SuppressWarnings("rawtypes")
        HashSet sessions = (HashSet) session.getServletContext().getAttribute("sessions");
        @SuppressWarnings("unchecked")
        Iterator<Session> iterator = sessions.iterator();
        PrincipalCollection pc = null;
        // 遍历sessions
        while (iterator.hasNext()) {
            HttpSession s = (HttpSession) iterator.next();
            User user = (User) s.getAttribute("user");
            if (user.getId() == id) {
                pc = (PrincipalCollection) s.getAttribute(String.valueOf(id));
                // 清空该用户权限缓存
                rolePermissionService.clearUserPermCache(pc);
                s.removeAttribute(String.valueOf(id));
                break;
            }
        }

        rolePermissionService.updateRolePermission(id, oldRoleIdList, newRoleIdList);
    }

    /**
     * 添加角色跳转
     */
    @RequiresPermissions("sys:role:add")
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createForm(Map model) {
        model.put("role", new Role());
        model.put("action", "create");
        return "system/roleForm";
    }

    /**
     * 添加角色
     */
    @ResponseBody
    @RequiresPermissions("sys:role:add")
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public void create(@Valid Role role) {
        roleService.save(role);
    }

    /**
     * 修改角色跳转
     */
    @RequiresPermissions("sys:role:update")
    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Integer id, Map model) {
        model.put("role", roleService.get(id));
        model.put("action", "update");
        return "system/roleForm";
    }

    /**
     * 修改角色
     */
    @ResponseBody
    @RequiresPermissions("sys:role:update")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public void update(@Valid @ModelAttribute("role") Role role) {
        roleService.save(role);
    }

    /**
     * 删除角色
     */
    @ResponseBody
    @RequiresPermissions("sys:role:delete")
    @RequestMapping(value = "delete/{id}")
    public void delete(@PathVariable("id") Integer id) {
        roleService.delete(id);
    }

    @ModelAttribute
    public void getRole(@RequestParam(value = "id", defaultValue = "-1") Integer id, Map model) {
        if (id != -1) {
            model.put("role", roleService.get(id));
        }
    }
}
